package org.huangrui.javase.io;

import org.junit.Test;

import java.io.*;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @Author hr
 * @Create 2025-11-08 0:44
 **/
public class T03BigFile {
    @Test
    public void test1(){
        String inputFilePath = "D:\\large_input.txt";
        String outputFilePath = "D:\\large_output.txt";

        try (
                FileInputStream fis = new FileInputStream(inputFilePath);
                BufferedInputStream bis = new BufferedInputStream(fis);
                FileOutputStream fos = new FileOutputStream(outputFilePath);
                BufferedOutputStream bos = new BufferedOutputStream(fos)
        ) {
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void test2(){
        Path inputPath = Paths.get("D:\\large_input.txt");
        Path outputPath = Paths.get("D:\\large_output.txt");

        try {
            // 读取文件内容
            byte[] fileContent = Files.readAllBytes(inputPath);
            // 写入文件内容
            Files.write(outputPath, fileContent);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void test3(){
        String inputFilePath = "D:\\large_input.txt";
        String outputFilePath = "D:\\large_output.txt";

        try (
                RandomAccessFile inputFile = new RandomAccessFile(inputFilePath, "r");
                FileChannel inputChannel = inputFile.getChannel();
                RandomAccessFile outputFile = new RandomAccessFile(outputFilePath, "rw");
                FileChannel outputChannel = outputFile.getChannel()
        ) {
            long fileSize = inputChannel.size();
            MappedByteBuffer inputBuffer = inputChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileSize);
            MappedByteBuffer outputBuffer = outputChannel.map(FileChannel.MapMode.READ_WRITE, 0, fileSize);

            for (int i = 0; i < fileSize; i++) {
                outputBuffer.put(i, inputBuffer.get(i));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
